<!--
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2024-03-27 18:44:17
 * @LastEditors: huangtianyang
 * @LastEditTime: 2024-05-11 15:35:40
 * @FilePath: \driving-training-admin\src\components\form\upload.vue
-->
<template>
    <el-upload
        :class="['avatar-uploader']"
        action="#"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :style="{ width: '178px', height: (178 * ratio[1]) / ratio[0] + 'px' }"
        v-loading="loading"
    >
        <template v-if="url">
            <img :src="url" v-if="fileType === 'image'" ref="imageRef" class="aa avatar" @load="onLoad" />
            <video :src="url" v-else class="avatar"></video>
        </template>
        <el-icon v-else class="avatar-uploader-icon">
            <Picture v-if="fileType === 'image'" />
            <VideoCamera v-else />
        </el-icon>
    </el-upload>
</template>
<script setup lang="ts">
import { reactive, ref, watchEffect } from 'vue'
import { UploadProps, ElMessage } from 'element-plus'
import { fileToBase64Async } from '@/utils/index'
import { fileUrl, uploadByBase64, uploadByFile, uploadPublicByBase64 } from '@/apis/upload/index'
//public 设置上传资源是公有还是私有 默认不传 私有
const props = defineProps(['fileType', 'dirType', 'sizeRatio', 'data', 'src', 'public'])
const emits = defineEmits(['change', 'load'])
const url = ref('')
const loading = ref(false)
let fileName = ''
const ratio = reactive([1, 1])
const imageRef = ref()

watchEffect(() => {
    url.value = ''
    if (props.data) {
        url.value = props.src
    }
    if (props.sizeRatio && props.sizeRatio.length === 2) {
        ratio.length = 0
        ratio.push(...props.sizeRatio)
    }
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    console.log('response', response)
    url.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload = (rawFile: any) => {
    console.log('rawFile.type', rawFile)
    fileName = rawFile.name.substring(0, rawFile.name.lastIndexOf('.'))

    if (props.fileType === 'image') {
        if (!['image/jpeg', 'image/png', 'image/jpg', 'image/svg+xml'].includes(rawFile.type)) {
            ElMessage.error('请上传PNG或者JPG格式')
            return false
        } else if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('请上传小于5M图片')
            return false
        }
        loading.value = true
        fileToBase64Async(rawFile).then((str: string) => {
            if (props.public) {
                //公有图片
                uploadPublicByBase64(str.split(',')[1], props.dirType).then((res: any) => {
                    loading.value = false
                    if (Number(res.data.code) === 200) {
                        url.value = res.data.result.url
                        emits('change', {
                            name: fileName,
                            url: res.data.result.url,
                            key: res.data.result.key
                        })
                    }
                })
            } else {
                //私有图片
                uploadByBase64(str.split(',')[1], props.dirType).then((res: any) => {
                    loading.value = false
                    if (Number(res.data.code) === 200) {
                        url.value = res.data.result.url
                        emits('change', {
                            name: fileName,
                            url: res.data.result.url,
                            key: res.data.result.key
                        })
                    }
                })
            }
        })
    } else if (props.fileType === 'video') {
        if (!['video/mp4'].includes(rawFile.type)) {
            ElMessage.error('请上传MP4格式')
            return false
        } else if (rawFile.size / 1024 / 1024 > 500) {
            ElMessage.error('请上传小于500M视频')
            return false
        }
        loading.value = true
        uploadByFile(rawFile, props.dirType).then(res => {
            loading.value = false
            if (Number(res.data.code) === 200) {
                url.value = res.data.result.url
                emits('change', {
                    name: fileName,
                    url: res.data.result.url,
                    key: res.data.result.key
                })
            }
        })
    }
    return false
}

const onLoad = (res: any) => {
    const w = res.target.naturalWidth
    const h = res.target.naturalHeight

    if (w / h > 1) {
        ratio[0] = 1
        ratio[1] = 1 / (w / h)
    } else {
        ratio[0] = 1 / (w / h)
        ratio[1] = 1
    }

    console.log('res', res, imageRef.value.naturalWidth, imageRef.value.naturalHeight)
}
</script>
<style scoped lang="scss">
.upload-box img,
.upload-box video {
    display: block;
    width: 100%;
    height: 100%;
}
.avatar-uploader-icon {
    font-size: 32px;
    color: #666;
}

.avatar {
    width: 100%;
    height: 100%;
}
</style>
